package com.mapfinal.server.auth;

import java.util.List;

import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.lambkit.common.ResultKit;
import com.lambkit.common.util.DateTimeUtils;
import com.lambkit.common.util.StringUtils;
import com.lambkit.db.mgr.MgrConstants;
import com.lambkit.db.mgr.MgrTable;
import com.lambkit.db.sql.condition.ConditionBuilder;
import com.lambkit.db.sql.condition.SqlBuilder;
import com.mapfinal.server.auth.model.AuthOrganization;
import com.mapfinal.server.auth.model.Role;
import com.mapfinal.server.auth.model.User;
import com.mapfinal.server.web.MapfinalServerController;

public class UserController extends MapfinalServerController {

	/**
	 * 数据详细页
	 */
	public void index() {
		MgrTable tbc = getTableView(User.service().getTableName(), true);
		Integer id = getParaToInt(0) == null ? getParaToInt("id") : getParaToInt(0);
		keepTable(tbc, User.service().findById(id));
		render("index.html");
	}
	
	/**
	 * 单条数据
	 */
	public void get() {
		getTableView(User.service().getTableName(), true);
		Integer id = getParaToInt(0) == null ? getParaToInt("id") : getParaToInt(0);
		User datas = User.service().findById(id);
		if(datas==null) {
			renderJson(ResultKit.json(0, "fail", null));
		} else {
			renderJson(ResultKit.json(1, "success", datas));
		}
	}
	
	/**
	 * 数据列表页
	 */
	public void list() {
		//getTableDefault(Users.service().getTableName(), true);
		getTable(User.service().getTableName(), MgrConstants.VIEW, true, "viewfldorder");
		render("list.html");
	}
	
	/**
	 * 分页
	 */
	public void page() {
		MgrTable tbc = getTable(User.service().getTableName(), MgrConstants.VIEW, true, "viewfldorder");
		if (tbc == null) {
			renderJson(ResultKit.json(0, "fail", "table config is null"));
			return;
		}
		ConditionBuilder cb = getConditionsSQL(tbc).build("");
		SqlBuilder sb = new SqlBuilder();
		String select = sb.appendSelect(tbc).build();
		sb.clear().appendFrom(tbc).appendConditions(cb);
		//排序
		String orderby = getPara("orderby");
		if(StrKit.notBlank(orderby)) sb.appendOrderBy(orderby);
		String sql = sb.build();
		Integer pNumber = getParaToInt("pageNum", getParaToInt("page", 1));
		Integer pSize =  getParaToInt("numPerPage", getParaToInt("limit", 15));
		Page<Record> page = Db.paginate(pNumber, pSize, select, sql, cb.getSqlParas());
		String type = getPara("rt", "default");
		if("default".equalsIgnoreCase(type)) {
			renderJson(ResultKit.json(1, "success", page));
		} else {
			renderJson(ResultKit.page(type, 1, "success", page.getTotalRow(), page.getList()));
		}
		
	}
	
	public void add() {
		render("add.html");
	}
	
	public void edit() {
		getTableView(User.service().getTableName(), true);
		Integer id = getParaToInt(0) == null ? getParaToInt("id") : getParaToInt(0);
		setAttr("model", User.service().findById(id));
		render("add.html");
	}
	
	public void save() {
		User env = getModel(User.class, "model");
		
		String userName = env.getUserLogin();
		String password = env.getUserPass();
		String nickName = env.getUserNicename();
		
		if (StrKit.isBlank(userName) || StrKit.isBlank(password) || StrKit.isBlank(nickName)) {
			renderJson(ResultKit.json(0, "fail", "用户名、密码或昵称不能为空"));
			return;
		}

		userName = userName.toLowerCase().trim();	// 邮件全部存为小写
		password = password.trim();
		nickName = nickName.trim();

		if (nickName.contains("@") || nickName.contains("＠")) { // 全角半角都要判断
			renderJson(ResultKit.json(0, "fail", "昵称不能包含 \"@\" 字符"));
			return;
		}
		if (nickName.contains(" ") || nickName.contains("　")) { // 检测是否包含半角或全角空格
			renderJson(ResultKit.json(0, "fail", "昵称不能包含空格"));
			return;
		}
		if (User.service().isNickNameExists(nickName)) {
			renderJson(ResultKit.json(0, "fail", "昵称已被注册，请换一个昵称"));
			return;
		}
		if (User.service().isUserNameExists(userName)) {
			renderJson(ResultKit.json(0, "fail", "用户名已被注册，如果忘记密码，可以使用密码找回功能"));
			return;
		}
		
		env.setUserPass(User.service().getPasswordMD5(env.getUserPass()));
		//modify201912221
		env.setUserStatus(1);
		//env.setUserStatus(2);
		//modify20201116
		if(env.getUserType() == null) {
			env.setUserType(2);
		}
		env.setCreateTime(DateTimeUtils.getCurrentTime());
		env.setUuid(StringUtils.uuid().toLowerCase());
		env.setUserType(2);
		
		boolean flag = env.save();
		if(flag) {
			renderJson(ResultKit.json(1, "success", env));
		} else {
			renderJson(ResultKit.json(0, "fail", "失败"));
		}
	}
	
	public void update() {
		User env = getModel(User.class, "model");
		String userName = env.getUserLogin();
		String password = env.getUserPass();
		String nickName = env.getUserNicename();
		
		if (StrKit.isBlank(userName) || StrKit.isBlank(password) || StrKit.isBlank(nickName)) {
			renderJson(ResultKit.json(0, "fail", "用户名、密码或昵称不能为空"));
			return;
		}
		
		String sql = "select id from lk_users where lower(user_nicename) = ? and id != ? limit 1";
		Integer id = Db.queryInt(sql, nickName, env.getId());
		if (id != null) {
			renderJson(ResultKit.json(0, "fail", "昵称已经存在，请输入别的昵称"));
			return;
		}

		userName = env.getUserLogin().toLowerCase().trim();
		sql = "select id from lk_users where lower(user_login) = ? and id != ? limit 1";
		id = Db.queryInt(sql, userName, env.getId());
		if (id != null) {
			renderJson(ResultKit.json(0, "fail", "邮箱已经存在，请输入别的昵称"));
			return;
		}
		
		if("lambkit-default-password-for-empty-post-to-server".equals(password)) {
			env.remove("user_pass");
		} else {
			env.setUserPass(User.service().getPasswordMD5(env.getUserPass()));
		}
		boolean flag = env.update();
		if(flag) {
			renderJson(ResultKit.json(1, "success",Db.findById("lk_users", env.getId())));
		} else {
			renderJson(ResultKit.json(0, "fail", "失败"));
		}
	}
	
	public void delete() {
		boolean flag = false;
		Integer id = getParaToInt(0) == null ? getParaToInt("id") : getParaToInt(0);
		User datas = User.service().findById(id);
		if(datas!=null) {
			flag = datas.delete();
		}
		if(flag) {
			renderJson(ResultKit.json(1, "success", "deleted"));
		} else {
			renderJson(ResultKit.json(0, "fail", "deleted"));
		}
	}
	
	/**
	 * 分配角色
	 */
	public void assignRoles() {
		Integer id = getParaToInt(0) == null ? getParaToInt("id") : getParaToInt(0);
		User account = User.service().findById(id);
		List<Role> roleList = Role.service().getAllRoles();
		User.service().markAssignedRoles(account, roleList);
		setAttr("account", account);
		setAttr("roleList", roleList);
		render("assign_roles.html");
	}
	
	/**
	 * 添加角色
	 */
	public void addRole() {
		Ret ret = User.service().addRole(getParaToInt("accountId"), getParaToInt("roleId"));
		renderJson(ret);
	}
	
	/**
	 * 删除角色
	 */
	public void deleteRole() {
		Ret ret = User.service().deleteRole(getParaToInt("accountId"), getParaToInt("roleId"));
		renderJson(ret);
	}
	
	public void assignOrganizations() {
		Integer id = getParaToInt(0) == null ? getParaToInt("id") : getParaToInt(0);
		User account = User.service().findById(id);
		List<AuthOrganization> roleList = AuthOrganization.service().getAllOrganizations();
		User.service().markAssignedOrganizations(account, roleList);
		setAttr("account", account);
		setAttr("orgList", roleList);
		render("assign_orgs.html");
	}
	
	/**
	 * 添加公司
	 */
	public void setOrganization() {
		Ret ret = User.service().setOrganization(getParaToLong("accountId"), getParaToInt("orgId"), getParaToInt("jobId"), getPara("jobs"));
		renderJson(ret);
	}
	
	/**
	 * 删除公司
	 */
	public void deleteOrganization() {
		Ret ret = User.service().deleteOrganization(getParaToLong("accountId"), getParaToInt("orgId"));
		renderJson(ret);
	}
}
